const url = require('url');
const got = require('@/utils/got');
const cheerio = require('cheerio');

const puppeteerGet = (url, cache, waitForSelector) =>
    cache.tryGet(url, async () => {
        const browser = await require('@/utils/puppeteer')();
        const page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', (request) => {
            request.resourceType() === 'document' ? request.continue() : request.abort();
        });
        let html;
        await page.goto(url, {
            waitUntil: 'domcontentloaded',
        });
        await page.waitForSelector(waitForSelector).then(async () => {
            html = await page.evaluate(() => document.documentElement.innerHTML);
        });
        await browser.close();
        return html;
    });

module.exports = async (ctx) => {
    const root_url = 'https://www.gongkaoleida.com/area/37';
    const html = await puppeteerGet(root_url, ctx.cache, 'div.notice-list');

    let list = [];
    const $ = cheerio.load(html);
    const lis = $('div.notice-list>ul.link-list>li');
    for(let i=0; i<lis.length; i++) {
        list.push(lis[i]);
    }

    const count = [];
    for (let i = 0; i < Math.min(list.length, 10); ++i) {
        count.push(i);
    }

    const items = await Promise.all(
        count.map((i) => {
            const item = cheerio.load(list[i])('li');
            const title = item.find('h5>a').first();
            const link = title.attr('href');

            // return puppeteerGet(link, ctx.cache, 'article.detail-info').then(html => {
            //     const content = cheerio.load(html);
            //     const post = content('article.detail-info');
            //     post.find('img[data-src]').each((_, ele) => {
            //         ele = content(ele);
            //         ele.attr('src', ele.attr('data-src'));
            //         ele.attr('alt', title.attr('title'));
            //         ele.attr('title', title.attr('title'));
            //         ele.removeAttr('class');
            //         ele.removeAttr('data-src');
            //     });

            //     const pubDate = new Date(content('div.date-source').find('time.date').text().trim() + ' GMT+8').toUTCString();

            //     return {
            //         title: title.attr('title'),
            //         link,
            //         pubDate,
            //         description: post.html(),
            //     };
            // });

            const dateStr = item.find('time').text().trim();
            let pubDate = new Date().toUTCString();
            if (/\d{4}-\d{2}-\d{2}/.test(dateStr)) {
                pubDate = new Date(`${dateStr} 00:00:00 GMT+8`).toUTCString();
            }

            return Promise.resolve({
                title: title.attr('title'),
                link: link,
                pubDate: pubDate,
                description: 'No description'
            })
        })
    );

    ctx.state.data = {
        title: '河北省公考雷达',
        link: root_url,
        item: items,
    };
};
